#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : test_login.py
@Author     : LeeCQ
@Date-Time  : 2020/8/29 10:08
"""
from common import *
from exc import LoginError, ElementNotFind
import unittest


class TestLogin(unittest.TestCase):

    def setUp(self) -> None:
        self.driver = chrome()

    def tearDown(self):
        try:
            self.driver.close()
        except:
            pass

    def test_login(self, ):
        """测试登录"""
        d = login(self.driver, 'test', '123456')
        d_t = d.find_element_by_css_selector('#topnav > li:nth-child(4) > a').text
        logger.debug(d_t)
        self.assertEqual(d_t, '安全退出', '登录成功')


def login(_driver: BaseWebDriver, user, pwd):
    """登录

    :param _driver: 任意一个WebDriver对象，
    :param user: 用户名
    :param pwd: 密码
    :return: 登录成功后的WebDriver对象
    """
    _driver.get(home)
    _driver.find_element_by_id('username').send_keys(user)
    _driver.find_element_by_id('password').send_keys(pwd)
    _driver.find_element_by_id('btnlogin').click()
    try:
        _driver.implicitly_wait(8)
        _driver.find_element_by_id('topnav')
        logger.info('登录成功')
        return _driver
    except ElementNotFind:
        _driver.close()
        raise LoginError(f'登录失败，检查配置；访问地址={home}, 用户名={user}, 密码={pwd}')


def login_easy(user, pwd):
    """简易登录

    :param user:
    :param pwd:
    :return:
    """

    return login(chrome(), user, pwd)


def login_default():
    """默认的登录方式"""

    return login_easy('admin', '123456')


if __name__ == '__main__':
    logger.addHandler(console_handler)
    unittest.main()
